package com.hellowx.manager.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hellowx.manager.mapper.GoodsMapper;
import com.hellowx.manager.pojo.Goods;
import com.hellowx.manager.service.GoodsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 *
 * @author MagicMushroom
 * @date 2021/7/17
 */
@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Integer save(Goods goods) {
         int i = goodsMapper.insertOne(goods);
        if (i>0){
            return goods.getGoodsId();
        }
        return -1;
    }

    @Override
    public List<Goods> getAll(IPage<Goods> goodsPage,Goods goods) {
        /*
        *  goodsRedisKey 组成部分
        *   goods:pageIndex_:pageSize_:catId_:brandId_:goodsName_
        * */

        String[] goodsRedisKeyArray=new String[]{
                "goods:pageIndex_"+goodsPage.getCurrent(),
                ":pageSize_"+goodsPage.getSize(),
                ":catId_",
                "brandId_",
                "goodsName_"
        };
        if (goods.getCatId()!=null){
            goodsRedisKeyArray[2]=goodsRedisKeyArray[2]+goods.getCatId();
        }
        if (goods.getBrandId()!=null){
            goodsRedisKeyArray[2]=goodsRedisKeyArray[2]+goods.getBrandId();
        }
        if (goods.getGoodsName()!=null){
            goodsRedisKeyArray[2]=goodsRedisKeyArray[2]+goods.getGoodsName();
        }
//        拼接字符串
        String goodsListKey = String.join("", goodsRedisKeyArray);
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();

        String goodsListJson = valueOperations.get(goodsListKey);
        if (!StringUtils.isEmpty(goodsListJson)){
            return JSON.parseArray(goodsListJson,Goods.class);
        }
        List<Goods> goodsList =  goodsMapper.selectAllByQueryConditions(goodsPage,goods);
        if (!CollectionUtils.isEmpty(goodsList)){
            valueOperations.set(goodsListKey,JSON.toJSONString(goodsList));
            return goodsList;
        }
        valueOperations.set(goodsListKey,"",60, TimeUnit.SECONDS);
        return null;
    }
}
